package com.xudow.app.newui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.newui.base.BaseUiActivity;
import com.xudow.app.ui.CartActivity;
import com.xudow.app.ui.LoginActivity;
import com.xudow.app.util.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

public class EditKeyWordActivity extends BaseUiActivity implements View.OnClickListener, TextWatcher, AdapterView.OnItemClickListener {
    @BindView(R.id.keyword)
    EditText keyword;

    @BindView(R.id.clean_recod_tv)
    TextView clean_recod_tv;

    @BindView(R.id.history_lv)
    ListView history_lv;

    @BindView(R.id.cancel_tv)
    TextView cancel_tv;

    @BindView(R.id.shopping_cartl_iv)
    ImageView shopping_cartl_iv;
    private List<String> recordlist;
    private File recordfile;
    private HistoryAdapter recordadapter;
    public String SEARCH_HISTORY="search_history.txt";
    private String record;
    ArrayList<String> templist;
    private int RECORD_COUNT=10;//保存记录条数
    public static int SEARCH_RESULT_CORD=200;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_key_word);

    }

    @Override
    protected void initData() {

        recordlist=new ArrayList<String>();
        recordfile=new File(getCacheDir().getAbsolutePath(),SEARCH_HISTORY);
        if (recordfile.exists()){
            try {
                templist=(ArrayList<String>)FileUtils.readFils(recordfile);
                Log.e("templist",(templist==null)+""+templist.size());
                recordlist.addAll(templist);
                Collections.reverse(templist);
                recordadapter=new HistoryAdapter(this,templist);
                history_lv.setAdapter(recordadapter);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (templist!=null){
            try {
                templist=(ArrayList<String>)FileUtils.readFils(recordfile);
                Log.e("templist",(templist==null)+""+templist.size());
                Collections.reverse(templist);
                recordadapter.setData(templist);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        recordlist.clear();
        if (null!=templist)
            templist.clear();
        recordlist=null;
        templist=null;
    }

    @Override
    protected void initListener() {
        cancel_tv.setOnClickListener(this);
        shopping_cartl_iv.setOnClickListener(this);
        clean_recod_tv.setOnClickListener(this);
        keyword.addTextChangedListener(this);//监听textwatcher(text内容变化)
        keyword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT||
                        actionId==EditorInfo.IME_ACTION_GO) {//监听键盘确定键
                    // TODO 保存记录、跳转课程列表（带关键字）
                    if (recordlist.size() == RECORD_COUNT) {//设置保存记录条数
                        recordlist.remove(0);
                    }


                    saveRecord(record);
                    goBackSearch();
                }
                return false;
            }
        });
        history_lv.setOnItemClickListener(this);
    }
    /**
     * 设置返回数据
     */
    private void goBackSearch(){
        setResult(SEARCH_RESULT_CORD,new Intent().putExtra("record",record));
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.cancel_tv://取消
                finish();
                break;
            case R.id.shopping_cartl_iv://购物车点击
                XApplication application = getMyApp();
                if (!application.isLogin()) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.putExtra("closeAfterLogin", true);
                    startActivity(intent);
                    return;
                }else{
                    Intent intent=new Intent(this,CartActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.clean_recod_tv://清除历史记录点击
                recordfile.delete();
                recordlist.clear();
                templist.clear();
                recordadapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
       record=s.toString().trim();
    }

    /**
     * 保存当前记录
     */
    private void saveRecord(String str) {
        try {
            Log.e("editkeyword", "saveRecord: " + str);
            if (!recordlist.contains(record)) {
                recordlist.add(record);
                FileUtils.writeFile(recordlist, recordfile);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            record=templist.get(position);
            goBackSearch();
    }

    class HistoryAdapter extends BaseAdapter{
        Context context;
        List<String> list;
        public HistoryAdapter(Context context,List<String> list){
            this.context=context;
            this.list=list;
        }
        public void setData(List<String> list){
            this.list=list;
            notifyDataSetChanged();
        }
        @Override
        public int getCount() {
            if (null==list||list.size()==0)
                return 0;
            else
                return list.size();
        }

        @Override
        public String getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView tv;
            if (null==convertView){
                convertView=View.inflate(EditKeyWordActivity.this,R.layout.item_search_history,null);
                tv=(TextView)convertView.findViewById(R.id.item_tv);
                convertView.setTag(tv);
            }else
                tv=(TextView)convertView.getTag();

            tv.setText(list.get(position));
            return convertView;
        }
    }
}
